package ph.greenova.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import ph.greenova.web.dto.AssignProjectDTO;
import ph.greenova.web.dto.ProjectDTO;

/**
 * Created By: adrian
 * Date Created: 6:03 AM 6/5/13
 */
@Controller
@RequestMapping(value = "projects")
public class ProjectController extends BaseController {

//    @Autowired

    @RequestMapping(value = {"/", ""}, method = RequestMethod.GET)
    public ModelAndView viewAllProjects(final ModelMap model) {

        model.addAttribute("projectList", getProjectService().getAllProjects());
        return new ModelAndView("viewProjects", model);
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public ModelAndView viewCreateProject(final ModelMap model) {

        model.addAttribute("projectForm", new ProjectDTO());
        return new ModelAndView("viewCreateProject", model);
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String createProject(final ModelMap model, @ModelAttribute("projectForm") ProjectDTO dto) {
        getProjectService().createNewProject(dto);
        return "redirect:/projects";
    }

    // Assignment related methods
    @RequestMapping(value = "assignments", method = RequestMethod.GET)
    public ModelAndView viewAssignments(@RequestParam(value = "projectId", required = true) final Long projectId, final ModelMap model) {

        AssignProjectDTO dto = new AssignProjectDTO();
        dto.setProjectId(String.valueOf(projectId));
        model.addAttribute("assignDTO", dto);
        model.addAttribute("notMembers", getProjectService().getAllNotMembers(projectId));

        model.addAttribute("projectMembers", getProjectService().getAllProjectMembers(projectId));
        return new ModelAndView("assignments", model);
    }

    @RequestMapping(value = "assign", method = RequestMethod.POST)
    @ResponseBody
    public String assignPersonToProject(@ModelAttribute("assignDTO") AssignProjectDTO assignProjectDTO) {
        if (assignProjectDTO.getPersonId() != null && assignProjectDTO.getProjectId() != null) {
            getProjectService().assignPersonToProject(Long.valueOf(assignProjectDTO.getProjectId()), Long.valueOf(assignProjectDTO.getPersonId()));
        }

        return "success";
    }

    @RequestMapping(value = "unassign", method = RequestMethod.POST)
    @ResponseBody
    public String unassignPersonToProject(@RequestParam("projectId") final Long projectId, @RequestParam("personId") final Long personId) {
        System.out.println(projectId + " " + personId);
        getProjectService().unassignPersonFromProject(projectId, personId);
        return "success";
    }

}
